#include "Portal.h"
#include "Level.h"
#include "Game.h"
#include "Player.h"
#include "Renderer.h"
#include "Dungeon.h"
#include "Tile.h"
#include "Util.h"

Portal::Portal(bool up, int portalNum, Level* level) : Obstacle(GT_OB_PORTAL) {
	m_blocking = false;
	m_up = up;
	m_portalNum = portalNum;
	m_level = level;
}

Portal::Portal(Tile* tile, std::ifstream& file) : Obstacle(GT_OB_PORTAL, file) {
	int* tokens = Util::intSplit(file);
	m_up = tokens[0] == 1;
	m_portalNum = tokens[1];
	m_blocking = false;
	m_level = tile->getLevel();
	m_level->loadPortal(this);
	delete[] tokens;
}

Portal::~Portal() {
}

void Portal::save(std::ofstream& file) const {
	file << getType(TH_GENERIC_TYPE) << "\n";
	Obstacle::save(file);
	file << (m_up ? 1 : 0) << " " << m_portalNum << "\n";
}

void Portal::render(float x, float y) {
	g_renderer->render(*this, x, y);
}

void Portal::takePortal(Player* player) {
	Level* level = m_level->getDungeon()->getLevel(m_level->getLevelNum() + (m_up ? -1 : 1));
	if(level != NULL) {
		player->getTile()->removeCharacter();
		level->placePlayer(player, !m_up, m_portalNum);
		player->modifyTurnCounter(DEFAULT_TURN_LENGTH*2);
	} else {
		m_level->getDungeon()->takePortal(player, this);
	}
	saveGame();
}
